from ..bot_plugin import Bot_plugin
from ..authorize_plugin.authorize_plugin import Group_manager
from ..authorize_plugin.authorize_plugin import Group_manager as Table_manager
from cqhttp import CQHttp
from bot_body import Bot_body
from tools.CQ_tools import img_url_to_CQCode

import re
import logging
import colorful
import time

class Plugin_nick(Bot_plugin):
    def __init__(self, bot_body: Bot_body, name="manage nicks"):
        Bot_plugin.__init__(self, bot_body, name=name)
        self.nick_manager = Table_manager(
            tbl="nicks",
            primary_column="user_id"
        )
        self.help_msg=r"""【昵称管理助手帮助】
0. 昵称帮助：显示本条信息【仅主人】
1. 昵称设置123456（别名）：设置对应QQ的昵称【仅主人】
2. 昵称删除123456：删除数据库中对应QQ的昵称【仅主人】
3. 昵称查询123456：查询QQ的昵称，如果数据库中没有，则查询QQ昵称【仅主人】"""
    
    def query_nick(self, user_id):
        '''
        根据user_id(qq号)返回数据库中的昵称。
        弱数据库中没有对应的昵称，则查询对应的QQ昵称，存入数据库与缓存中
        '''
        ret = self.bot.get_stranger_info(user_id=user_id)
        user_name = ret['nickname']
        nick = self.nick_manager.query(user_id, 'nick')
        if nick == None:
            self.set_nick(user_id, user_name)
            return user_name
        else:
            return nick

    def set_nick(self, user_id, new_nick):
        return self.nick_manager.update(user_id, 'nick', new_nick)

    def delete_nick(self, user_id):
        return self.nick_manager.delete(user_id)

    def handle_msg(self, context):
        bot = self.bot
        from tools.CQ_tools import group_msg_level
        msg_level = group_msg_level.judge(context, master_qqs=self.master_qqs)
        if context['raw_message'] in ['昵称帮助'] and msg_level >= group_msg_level.MASTER:
            bot.send(context, self.help_msg)
            return
        if context['raw_message'][:4] == '昵称设置' and msg_level >= group_msg_level.MASTER:
            pattern = r"昵称设置(?P<qq>\d{5,10})[\(（](?P<nick>.+)[\)）]"
            ret = re.match(pattern, context['raw_message'])
            if ret == None:
                bot.send(context, self.help_msg)
            else:
                res = ret.groupdict()
                old_nick = self.query_nick(res['qq'])
                ret = self.set_nick(res['qq'], res['nick'])
                if ret:
                    reply_msg = r"""QQ{qq}的昵称从{old_nick}修改为{new_nick}！""".format(
                        qq=res['qq'], old_nick = old_nick, new_nick = res['nick']
                    )
                else:
                    reply_msg = r"""QQ{qq}的昵称修改失败！""".format(
                        qq=res['qq']
                    )
                bot.send(context,reply_msg)
                return
        if context['raw_message'][:4] == '昵称删除' and msg_level >= group_msg_level.MASTER:
            pattern = r"昵称删除(?P<qq>\d{5,10})"
            ret = re.match(pattern, context['raw_message'])
            if ret == None:
                bot.send(context, self.help_msg)
            else:
                res = ret.groupdict()
                ret = self.delete_nick(user_id=res['qq'])
                if ret:
                    reply_msg = r"""已经成功删除数据库中QQ{qq}的昵称！""".format(
                        qq=res['qq']
                    )
                else:
                    reply_msg = r"""QQ{qq}的昵称删除失败！""".format(
                        qq=res['qq']
                    )
                bot.send(context, reply_msg)
                return
        if context['raw_message'][:4] == '昵称查询' and msg_level >= group_msg_level.MASTER:
            pattern = r'昵称查询(?P<qq>\d{5,10})'
            ret = re.match(pattern, context['raw_message'])
            if ret == None:
                bot.send(context, self.help_msg)
            else:
                res = ret.groupdict()
                ret = self.query_nick(user_id=res['qq'])
                reply_msg = r"QQ{}的昵称是：{}".format(res['qq'], ret)
                bot.send(context, reply_msg)
            return


